package site.kitcheng.springboottest.infra.utils;

import site.kitcheng.springboottest.infra.constant.BaseConstant;

import javax.crypto.Cipher;
import java.security.PrivateKey;
import java.util.Base64;

/**
 * ClassName: RSADecryptWithSalt
 * Package: site.kitcheng.springboottest.infra.utils
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/2/24 11:37
 * @Version 1.0
 */
public class RSADecryptWithSalt {
    public static String decryptWithSalt(String encryptedDataWithSalt, PrivateKey privateKey) throws Exception {
        // 分离盐值和加密数据
        String[] parts = encryptedDataWithSalt.split(BaseConstant.PASSWORD_SEPARATOR);
        String salt = parts[0];
        String encryptedData = parts[1];

        // 使用RSA私钥解密
        Cipher cipher = Cipher.getInstance(BaseConstant.ENCRYPTION_ALGORITHMS);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));

        // 得到拼接的明文（盐值+原始数据）
        String decryptedString = new String(decryptedData);

        // 移除盐值，得到原始数据
        return decryptedString.substring(salt.length());
    }

}
